# -*-coding:utf-8-*-

from werkzeug.routing import BaseConverter
from flask import session, jsonify, g
from Ihome.utils.response_code import RET
import functools


# 定义正则的转换器
class RegexConverter(BaseConverter):
    def __init__(self, url_map, *args,**kwargs):
        super(RegexConverter, self).__init__(url_map)
        self.regex = args[0]


def login_required(f):
    '''判断用户是否登录的装饰器'''

    @functools.wraps(f)#修饰内层函数,以防止当前装饰器去修改被装饰函数的__name__属性
    def wapper(*args, **kwargs):
        user_id = session.get('user_id')
        if not user_id:
            # 直接返回没有登录的json
            return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
        else:
            g.user_id = user_id
            return f(*args, **kwargs)

    return wapper
